package com.ktjiaoyu.crm.config.shiro;

import com.ktjiaoyu.crm.pojo.Right;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RightService;
import com.ktjiaoyu.crm.service.RoleService;
import com.ktjiaoyu.crm.service.UserService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    UserService userService;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    RoleService roleService;
    @Resource
    RightService rightService;

    //授权 查询登录用户所拥有的权限和角色
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用了doGetAuthorizationInfo方法");
        //获取登录用户
        User user=(User)principalCollection.getPrimaryPrincipal();

        //权限信息对象 （角色，权限）
        SimpleAuthorizationInfo simpleAuthorizationInfo=
                new SimpleAuthorizationInfo();
        //获取登录用户角色
//        Role role=user.getRole();
        Role role=roleService.getRoleByUsrId(user.getUsrId());
        simpleAuthorizationInfo.addRole(role.getRoleName());
        //获取登录用户权限
//        List<Right> rights = role.getRights();
        List<Right> rights = rightService.findRightsByRoleId(role.getRoleId());
        if(rights!=null){
            for (Right right : rights) {
                simpleAuthorizationInfo.addStringPermission(right.getRightCode());
            }
        }



//        simpleAuthorizationInfo.addStringPermission("用户列表");
//        if("管理员".equals(user.getRole().getRoleName())){
//            simpleAuthorizationInfo.addStringPermission("用户添加");
//            simpleAuthorizationInfo.addStringPermission("用户保存");
//            simpleAuthorizationInfo.addStringPermission("用户编辑");
//            simpleAuthorizationInfo.addStringPermission("用户修改");
//            simpleAuthorizationInfo.addStringPermission("用户删除");
//        }
        return simpleAuthorizationInfo;
    }

    //认证 根据用户名查询用户信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户信息
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        //1.为每一个用户再redis中存储一个计数器
        ValueOperations<String, String> vo = stringRedisTemplate.opsForValue();
        vo.increment("shiro_login_count_"+token.getUsername(),1);
        //2.判断计数器
        if(Integer.parseInt(vo.get("shiro_login_count_"+token.getUsername()))>5){
            //冻结用户
            vo.set("shiro_is_lock_"+token.getUsername(),"LOCK",1, TimeUnit.HOURS);
            //计数器删除
            stringRedisTemplate.delete("shiro_login_count_"+token.getUsername());
        }
        //3.判断用户是否被冻结
        if("LOCK".equals(vo.get("shiro_is_lock"+token.getUsername()))){
            throw new DisabledAccountException("账号被冻结");
        }

        //查询数据库
        User user = userService.getUserByUsrName(token.getUsername());
        if(user==null){
            throw new UnknownAccountException("账号不存在");
        }
        if(user.getUsrFlag()==0){
            throw new LockedAccountException("账号被锁定");
        }
        return new SimpleAuthenticationInfo(user,user.getUsrPassword(), ByteSource.Util.bytes("czkt"),getName());
    }

    /**
     * 清空当前登录用户的权限缓存 ，使我们修改了权限能够立即生效
     */
    public void clearMyCachedAuthorizationInfo(){
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

    public void clearAllCacheAuthorizationInfo(){
        //判断有没有用权限缓存
        if(this.isAuthorizationCachingEnabled()){
            //1.获取缓存管理器
            CacheManager cacheManager=this.getCacheManager();
            if(cacheManager!=null){
                //2.获取缓存的名称
                String authorizationCacheName = this.getAuthorizationCacheName();
                //3.清空指定名称的缓存
                Cache<Object, Object> cache = cacheManager.getCache(authorizationCacheName);
                if(cache!=null){
                    cache.clear();
                }
            }
        }
    }
}
